//
//  AppDelegate.m
//  koubei
//
//  Created by 朱圳 on 2018/4/1.
//  Copyright © 2018年 朱圳. All rights reserved.
//

#import "AppDelegate.h"
#import "WRNavigationBar.h"

#import "LoginViewController.h"//登录
#import "UserManager.h"//学生端管理
#import "ZTabBarController.h"
#import "JWUserManager.h"//教务端管理
#import "JWZHMainTabar.h"
#import "GRUserManager.h"//研究生端管理
#import "ZHMainTabar.h"

#import "JPUSHService.h"
#import <AdSupport/AdSupport.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

     [self setAPNs];
      NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID);
    }];
    [self setNavBarAppearence];
    [NSThread sleepForTimeInterval:2.0];//设置启动页面时间
    [self setDuankou];
    
return YES;
    
}

/**
 判断是否登录 进入不同端口 classification 1学生端2研究生端3教务端
 */
-(void)setDuankou{
//
        NSString *classification = [[NSUserDefaults standardUserDefaults] objectForKey:@"classification"];
        BOOL islogin = [UserManager isLogining];
        BOOL isJWlogin = [JWUserManager isJWLogining];
        BOOL isGRlogin = [GRUserManager isGRLogining];
    if (islogin || isJWlogin ||isGRlogin) {

        if ([classification isEqualToString:@"student"]) {
            ZTabBarController * tabbar = [[ZTabBarController alloc]init];
            [[UIApplication sharedApplication].delegate.window setRootViewController:tabbar];
        }else if ([classification isEqualToString:@"2"]){
            ZHMainTabar * tabbar = [[ZHMainTabar alloc]init];
            [[UIApplication sharedApplication].delegate.window setRootViewController:tabbar];
        }else if ([classification isEqualToString:@"3"]){
            JWZHMainTabar * tabbar = [[JWZHMainTabar alloc]init];
            [[UIApplication sharedApplication].delegate.window setRootViewController:tabbar];
        }else{
            LoginViewController *lookVC = [[LoginViewController alloc]init];
            self.window.backgroundColor=[UIColor whiteColor];
            UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:lookVC];
            self.window = [[UIWindow alloc]init];
            self.window.frame = [UIScreen mainScreen].bounds;
           
            [self.window setRootViewController:nav];
            [self.window makeKeyAndVisible];
        }

    }else{
        LoginViewController *lookVC = [[LoginViewController alloc]init];
        self.window.backgroundColor=[UIColor whiteColor];
        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:lookVC];
      
        self.window = [[UIWindow alloc]init];
        self.window.frame = [UIScreen mainScreen].bounds;
        [self.window setRootViewController:nav];
        [self.window makeKeyAndVisible];
    }
}

-(void)setAPNs{
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"koubei"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}
    - (void)setNavBarAppearence
    {
        // 设置导航栏默认的背景颜色
        [WRNavigationBar wr_setDefaultNavBarBarTintColor:dominantColor];
        // 设置导航栏所有按钮的默认颜色
        // [WRNavigationBar wr_setDefaultNavBarTintColor:[UIColor whiteColor]];
        // 设置导航栏标题默认颜色
        // [WRNavigationBar wr_setDefaultNavBarTitleColor:[UIColor whiteColor]];
        // 统一设置状态栏样式
        [WRNavigationBar wr_setDefaultStatusBarStyle:UIStatusBarStyleLightContent];
        // 如果需要设置导航栏底部分割线隐藏，可以在这里统一设置
        [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
    }

#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        
        [JPUSHService handleRemoteNotification:userInfo];
        
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support 消息响应
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
@end
